package com.frank.project.web.controller.system;

import com.frank.common.annotation.Log;
import com.frank.common.constant.UserConstants;
import com.frank.common.core.controller.BaseController;
import com.frank.common.core.domain.AjaxResult;
import com.frank.common.core.domain.Ztree;
import com.frank.common.enums.BusinessType;
import com.frank.common.utils.StringUtils;
import com.frank.project.system.domain.entity.SysOrg;
import com.frank.project.system.domain.entity.SysUser;
import com.frank.project.system.service.ISysOrgService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 组织信息
 * 
 * @author frank
 */
@Controller
@RequestMapping("/system/org")
public class SysOrgController extends BaseController
{
    private String prefix = "system/org";

    @Autowired
    private ISysOrgService orgService;

    @RequiresPermissions("system:org:view")
    @GetMapping()
    public String org()
    {
        return prefix + "/org";
    }

    @RequiresPermissions("system:org:list")
    @PostMapping("/list")
    @ResponseBody
    public List<SysOrg> list(SysOrg org)
    {
        List<SysOrg> orgList = orgService.selectOrgList(org);
        return orgList;
    }

    /**
     * 新增组织
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    {
        if (!getSysUser().isAdmin() || parentId.longValue() > 0L)
        {
//            parentId = getSysUser().getOrgId();
            mmap.put("org", orgService.selectOrgById(parentId));
        }
        return prefix + "/add";
    }

    /**
     * 新增保存组织
     */
    @Log(title = "组织管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:org:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysOrg org)
    {
        if (!orgService.checkOrgNoUnique(org))
        {
            return error("新增组织'" + org.getOrgNo() + "'失败，组织编号已存在");
        }
        else if (!orgService.checkOrgNameUnique(org))
        {
            return error("新增组织'" + org.getOrgName() + "'失败，组织名称已存在");
        }
        org.setCreateBy(getLoginName());
        return toAjax(orgService.insertOrg(org));
    }

    /**
     * 修改组织
     */
    @RequiresPermissions("system:org:edit")
    @GetMapping("/edit/{orgId}")
    public String edit(@PathVariable("orgId") Long orgId, ModelMap mmap)
    {
        orgService.checkOrgDataScope(orgId);
        SysOrg org = orgService.selectOrgById(orgId);
        if (StringUtils.isNotNull(org) && 0L == org.getParentId().longValue())
        {
            org.setParentName("无");
        }
        mmap.put("org", org);
        return prefix + "/edit";
    }

    /**
     * 修改保存组织
     */
    @Log(title = "组织管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:org:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysOrg org)
    {
        Long orgId = org.getOrgId();
        orgService.checkOrgDataScope(orgId);
        if (!orgService.checkOrgNoUnique(org))
        {
            return error("修改组织'" + org.getOrgNo() + "'失败，组织编号已存在");
        }
        else if (!orgService.checkOrgNameUnique(org))
        {
            return error("修改组织'" + org.getOrgName() + "'失败，组织名称已存在");
        }
        else if (org.getParentId().equals(orgId))
        {
            return error("修改组织'" + org.getOrgName() + "'失败，上级组织不能是自己");
        }
        else if (StringUtils.equals(UserConstants.ORG_DISABLE, org.getStatus()) && orgService.selectNormalChildrenOrgById(orgId) > 0)
        {
            return AjaxResult.error("该组织包含未停用的子组织！");
        }
        org.setUpdateBy(getLoginName());
        return toAjax(orgService.updateOrg(org));
    }

    /**
     * 删除
     */
    @Log(title = "组织管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:org:remove")
    @GetMapping("/remove/{orgId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("orgId") Long orgId)
    {
        if (orgService.selectOrgCount(orgId) > 0)
        {
            return AjaxResult.warn("存在下级组织,不允许删除");
        }
        if (orgService.checkOrgExistUser(orgId))
        {
            return AjaxResult.warn("组织存在用户,不允许删除");
        }
        orgService.checkOrgDataScope(orgId);
        return toAjax(orgService.deleteOrgById(orgId));
    }

    /**
     * 校验组织名称
     */
    @PostMapping("/checkOrgNameUnique")
    @ResponseBody
    public boolean checkOrgNameUnique(SysOrg org)
    {
        return orgService.checkOrgNameUnique(org);
    }

    /**
     * 校验组织编号
     */
    @PostMapping("/checkOrgNoUnique")
    @ResponseBody
    public boolean checkOrgNoUnique(SysOrg org)
    {
        return orgService.checkOrgNoUnique(org);
    }

    /**
     * 选择组织树
     * 
     * @param orgId 组织ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = { "/selectOrgTree/{orgId}", "/selectOrgTree/{orgId}/{excludeId}" })
    public String selectOrgTree(@PathVariable("orgId") Long orgId,
            @PathVariable(value = "excludeId", required = false) Long excludeId, ModelMap mmap)
    {
        mmap.put("org", orgId.longValue() == 0L ? null : orgService.selectOrgById(orgId));
        mmap.put("excludeId", excludeId);
        return prefix + "/tree";
    }

    /**
     * 加载组织列表树（排除下级）
     */
    @GetMapping("/treeData/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId)
    {
        SysOrg org = new SysOrg();
        org.setExcludeId(excludeId);
        List<Ztree> ztrees = orgService.selectOrgTreeExcludeChild(org);
        return ztrees;
    }
}
